package com.hongtao3.hsync;

import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Enumeration;
import java.util.Properties;

public class HttpUtil {
	 public static String http_build_query(Properties data) {
		   StringBuffer buf = new StringBuffer();
		   Enumeration names = data.propertyNames();
		   while (names.hasMoreElements()) {
			      String name = (String) names.nextElement();
			      String value =data.getProperty(name);
	            try {
					buf.append(URLEncoder.encode(name,"utf-8") + "=" + URLEncoder.encode(value,"utf-8"));
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
			      if (names.hasMoreElements()) buf.append("&");
			}
		    return buf.toString();
		  }
	  
	  public static String httpPost(String urlStr,Properties data,Properties headers,java.io.File f) throws Exception{
			URL url = new URL(urlStr);
			HttpURLConnection conn=(HttpURLConnection)url.openConnection();
			conn.setRequestMethod("POST");
			conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
	       conn.setRequestProperty("Connection", "Keep-Alive");
	       conn.setRequestProperty("User-Agent", "hsync/java");
	       
	       if(headers!=null){
		       Enumeration headers_names = headers.propertyNames();
		       while(headers_names.hasMoreElements()){
		    	    String name = (String) headers_names.nextElement();
				    String value =data.getProperty(name);
		    	    conn.setRequestProperty(name, value);
		        }
	       }
	       
	       conn.setUseCaches( false);
	       conn.setDoOutput(true);
	       conn.setDoInput(true);
	      
	       System.out.println("--------------------------------->");
	       System.out.println("url:"+urlStr+"\n");
		   Enumeration names = data.propertyNames();
		   while (names.hasMoreElements()) {
			      String name = (String) names.nextElement();
			      String value =data.getProperty(name);
			      System.out.println(name+":"+value);
			      
			}
		   System.out.println("<---------------------------------");
	       
		    PrintWriter out = new PrintWriter(conn.getOutputStream());
		    out.print(http_build_query(data));
		    out.flush();
		    out.close();
		     
		     conn.connect();
		     int code=conn.getResponseCode();
		     System.out.println("responseCode:"+code);
		     String line;
		     StringBuffer sb=new StringBuffer();
		     if(code==HttpURLConnection.HTTP_OK){
			     BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(),"utf-8"));
			   	 FileOutputStream output = null;
			  	 if(f!=null){
		    	    	output=new FileOutputStream(f); 
			  	  }
			  	   while ((line = reader.readLine()) != null) {
			  		   if(f==null){
			  			   sb.append(line+"\n");
			  		   }else{
			  			   output.write(line.getBytes());
			  		   }
			  	   }
			  	   reader.close();
		     }else{
			  	   BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getErrorStream(),"utf-8"));
			  	   while ((line = reader.readLine()) != null) {
			  		  sb.append(line+"\n");
			  	   }
			  	   reader.close();
			  	   conn.disconnect();
			  	   throw new Exception(sb.toString().trim());
		     }
		     conn.disconnect();
		     String s=sb.toString().trim();
			  System.out.println("================================>");
			  System.out.println(s);
			  System.out.println("<================================\n");
		    return s;
		}
}
